package jxc.servlet.user;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import eu.base.security.Encrypt;

import jxc.base.helper.UserAuthenticator;
import jxc.data.hibernate.dao.OperatorDAO;
import jxc.data.hibernate.pojo.Operator;

/**
 * Servlet implementation class Passwd
 */
@WebServlet("/user/passwd")
public class Passwd extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public Passwd() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * 获取当前用户
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		Operator op=UserAuthenticator.getUser(request);
		request.setAttribute("op", op);
		request.getRequestDispatcher("/user/passwd.jsp").forward(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String id=request.getParameter("user");
		String name=request.getParameter("name");
		String op=request.getParameter("op");
		String np=request.getParameter("np");
		String npc=request.getParameter("npc");
		OperatorDAO dao=new OperatorDAO();
		Operator oper=dao.getByUsername(id);
		if(oper==null){
			response.sendError(500,"User Not Found");
			return;
		}
		if(!oper.getPassword().equals(Encrypt.md5(op))){
			request.setAttribute("message", "旧密码不正确");
			doGet(request, response);
			return;
		}
		if(np==null||!np.equals(npc)){
			request.setAttribute("message", "两次密码不匹配");
			doGet(request, response);
			return;
		}
		oper.setName(name);
		oper.setPassword(Encrypt.md5(np));
		dao.update(oper);
		dao.commit();
		request.setAttribute("message", "更新成功");
		doGet(request, response);
	}

}
